package org.ky.generator.component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.runtime.RuntimeConstants;
import org.ky.generator.base.DefaultGenerator;
import org.ky.generator.config.DatabaseTableConfig;
import org.ky.generator.config.GeneratorCofig;
import org.ky.generator.config.PackageConfig;
import org.ky.generator.util.AttributeHelper;
import org.ky.generator.util.JdbcHelper;
import org.ky.generator.util.PropertyHelper;

import com.raddle.jdbc.callback.ConnectionCallback;
import com.raddle.jdbc.meta.table.ColumnInfo;
import com.raddle.jdbc.meta.table.TableInfo;
import com.raddle.jdbc.meta.table.TableMetaHelper;

/**
 * 实体类生成器
 * 
 * @author K.y
 * @since 2018-12-06
 *
 */
public class ModelGenerator extends DefaultGenerator {
	/** Java实体类生成模版 */
	private static final String TPL_MODEL = "template/bean/model.vm";
	public static ModelGenerator modelGenerator = new ModelGenerator();

	private ModelGenerator() {
	}

	public static ModelGenerator getInstance() {
		if (modelGenerator == null)
			modelGenerator = new ModelGenerator();
		return modelGenerator;
	}

	@SuppressWarnings("unchecked")
	@Override
	public void generator() {
		logger.debug("开始生成实体类");
		try {
			Velocity.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
					"org.apache.velocity.runtime.log.Log4JLogChute");
			Velocity.setProperty("runtime.log.logsystem.log4j.logger", "root");
			Properties p = new Properties();
			p.load(this.getClass().getResourceAsStream("/velocity.properties"));
			Velocity.init(p);
			List<TableInfo> tableInfoList = (List<TableInfo>) JdbcHelper.createJdbcTemplate()
					.execute(new ConnectionCallback() {
						public Object doInConnection(Connection con) throws SQLException {
							TableMetaHelper metaHelper = new TableMetaHelper(con);
							List<TableInfo> tableinfo = metaHelper.getTableInfo(DatabaseTableConfig.getGenTables(),
									null, new String[] { "TABLE" });
							return tableinfo;
						}
					});
			Pattern tableNameRegx = Pattern.compile("[^_]+_(.*)");
			for (TableInfo tableInfo : tableInfoList) {
				Matcher matcher = tableNameRegx.matcher(tableInfo.getTableName());
				if (!matcher.matches()) {
					// continue;
				}
				if (true) { // id属性已经不需要了
					for (ColumnInfo info : tableInfo.getColumnInfos()) {
						if (PropertyHelper.in(info.getColumnName(), "id")) {
							tableInfo.getColumnInfos().remove(info);
							break;
						}
					}
				}
				tableInfo.setTableName(tableInfo.getTableName());
				VelocityContext context = new VelocityContext();
				// 设置要填充的数据内容
				context.put("package", PackageConfig.getModelPath());
				context.put("baseJsonPackage", PackageConfig.getBaseJsonPath());
				context.put("baseJsonClass", PackageConfig.getClsBaseJson());
				context.put("tableInfo", tableInfo);
				context.put("attrHelper", new AttributeHelper());
				Template template = null;
				template = Velocity.getTemplate(TPL_MODEL);
				Writer writer = new OutputStreamWriter(
						new FileOutputStream(new File(PackageConfig.mkdirsPackagePath(PackageConfig.getOnlyModel()),
								AttributeHelper.getClassName(tableInfo.getTableName()) + ".java")),
						GeneratorCofig.UTF8);
				template.merge(context, writer);
				writer.flush();
				writer.close();
			}
		} catch (Exception e) {
			logger.error("实体类生成器异常", e);
			e.printStackTrace();
		}

	}
}
